<template>
  <div class="add-block">
    <div class="top-botton">
      <slot name="top-botton"></slot>
    </div>
    <editForm
      :formConfig="listItemConfig"
      ref="listItemForm"
      :formData="editFormData"
    ></editForm>

    <div class="tebleDiv">
      <!-- <editTable :tableSetting="partsDetails" :hideBtn="hideBtn" ref="partsTable"></editTable> -->
      <editTableNew
        :tableSetting="partsDetails"
        :hideBtn="changeContent ? false : disabledBtn"
        ref="partsTable"
        @handleClickAdd="addParts"
      ></editTableNew>
    </div>
    <div class="tebleDiv">
      <div class="attachConten" v-if="orderType == 'defect'">
        <div class="attachTitle">
          <span class="redPoint">*</span>完工图片:
        </div>
        <div class="tebleDiv">
          <attachFormNew
            style="width: 60%"
            :disabled="disabledBtn"
            :attachSetting="imageSetting"
            isDelete
            ref="imageFile"
          ></attachFormNew>
        </div>
      </div>
      <div class="attachConten">
        <div class="attachTitle">附件:</div>
        <div class="tebleDiv">
          <attachFormNew
            style="width: 60%"
            :disabled="disabledBtn"
            :attachSetting="attachSetting"
            isDelete
            ref="performFile"
          ></attachFormNew>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getPresetParamsApi, //获取设备参数
} from "@/api/common";
import { serchEqBackup } from "@/api/equipmentLedger/equipmentBackup";
export default {
  props: {
    formData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    orderStatus: {
      type: String,
      default: "",
    },
    orderType: {
      type: String,
      default: "",
    },
    pageType: {
      type: String,
      default: "",
    },
    hideBtn: {
      type: Boolean,
      default: false,
    },
    //仅作为信息展示
    showOnly: {
      type: Boolean,
      default: false,
    },
    planTime: {
      type: Object,
      default: () => {
        return {};
      },
    },
    changeContent: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    disabledBtn() {
      return this.hideBtn || this.pageType == "detail";
    },
  },
  watch: {
    formData: {
      handler(val) {
        this.init();
      },
      deep: true,
      immediate: true,
    },
    hideBtn: {
      handler(val) {
        this.init();
      },
    },
  },
  components: {},
  data() {
    return {
      editFormData: {},
      isDownloadOp: [
        { label: "是", value: 1 },
        { label: "否", value: 0 },
      ],
      partsData: {},
      //附件设置
      attachSetting: {
        businessId: "", //单据的ID
        businessType: "report",
      },
      //完工图片
      imageSetting: {
        businessId: "", //单据的ID
        businessType: "image",
      },
      showTable: false,
      listItemConfig: {
        itemArr: [
          {
            type: "device", //device\deviceClassify
            label: "缺陷设备",
            prop: "equipmentName",
            idsStr: "equipmentId",
            placeholder: "请选择设备",
            required: true,
            methods: (arr) => {
              this.currentDevice = arr[0] || {};
              let { id, name, major, typeId } = arr[0];
              if (arr.length != 0) {
                this.moveData = {
                  paramOldName: name,
                };
                //获取设备专业
                let form = { equipmentId: id, typeId };
                this.setDeptManage(form);
              }
            },
            span: 8,
          },
          {
            type: "select",
            label: "专业",
            prop: "majorId",
            required: true,
            selectOption: this.$store.getters["dirtData"]("common_major"),
            formatter: (val) => {
              return this.$store.getters["fineDirtDataName"](
                "common_major",
                val
              );
            },
            methods: (obj) => {},
            span: 8,
          },
          {
            type: "select",
            label: "缺陷描述是否准确",
            prop: "trueStatus",
            required: true,
            selectOption: [
              {
                name: "准确",
                label: "准确",
                value: "1",
              },
              {
                name: "不准确",
                label: "不准确",
                value: "0",
              },
            ],
            methods: (obj) => {},
            span: 8,
          },
          {
            type: "select",
            label: "缺陷原因类型",
            prop: "reasonType",
            required: true,
            selectOption: this.$store.getters["dirtData"](
              "order_defect_reason"
            ),
            formatter: (val) => {
              return this.$store.getters["fineDirtDataName"](
                "order_defect_reason",
                val
              );
            },
            methods: (obj) => {},
            span: 8,
          },
          {
            label: "缺陷原因",
            prop: "reason",
            type: "textarea",
            maxlength: "500",
            required: true,
            span: 24,
            rows: 4,
          },
          {
            label: "实际执行时间",
            prop: "factTime",
            type: "datetimerange", //datetimerange
            required: true,
            pickerOptions: {
              // disabledDate(time) {}
            },
            methods: (obj) => {
              //判断实际时间是否在计划时间内
              let { startTime, endTime } = this.planTime;
              if (
                Date.parse(startTime) > Date.parse(obj[0]) ||
                Date.parse(endTime) < Date.parse(obj[1])
              ) {
                this.$message.warning("实际执行时间不在计划时间内！");
              }
            },
            span: 8,
          },
          {
            /* 缺陷工单、正常维护 */
            label: "工作负责人",
            prop: "leaderName", //多选时，字段要为数组类型
            propArr: "leaderArr",
            idsStr: "leader",
            orgNameStr: "workDeptName",
            orgIdStr: "workDept",
            multiple: false, //是否多选
            isOutOrg: 0, //是否是外单位
            allowCreate: false, //是否允许创建条目
            option: [], //当前选中的项
            type: "user", //类型
            trigger: "change",
            methods: (obj) => {},
            required: true,
            isHide: true,
            span: 8,
          },
          {
            type: "select",
            label: "是否外部派工",
            prop: "outDispatch",
            required: true,
            isHide: true,
            selectOption: [
              {
                name: "是",
                label: "是",
                value: "1",
              },
              {
                name: "否",
                label: "否",
                value: "0",
              },
            ],
            span: 8,
          },
          {
            label: "维护内容",
            prop: "context",
            type: "textarea",
            maxlength: "500",
            span: 24,
            rows: 4,
            required: true,
          },
          {
            type: "select",
            label: "是否遗留问题",
            prop: "remainStatus",
            required: true,
            selectOption: [
              {
                name: "是",
                label: "是",
                value: "1",
              },
              {
                name: "否",
                label: "否",
                value: "0",
              },
            ],
            methods: (obj) => {
              console.log(obj);
              if (obj.value == "1") {
                this.$set(this.listItemConfig.itemArr[10], "isHide", false);
              } else {
                this.$set(this.listItemConfig.itemArr[10], "isHide", true);
              }
              // this.changeConfig(obj);
            },
            span: 8,
          },
          {
            type: "select",
            label: "是否可投入使用",
            prop: "runStatus",
            required: true,
            selectOption: [
              {
                name: "可投入使用",
                label: "可投入使用",
                value: "1",
              },
              {
                name: "不可投入使用",
                label: "不可投入使用",
                value: "0",
              },
            ],
            methods: (obj) => {
              // this.changeConfig(obj);
            },
            span: 8,
          },
          {
            label: "遗留问题",
            prop: "remainDesc",
            type: "textarea",
            maxlength: "500",
            isHide: true,
            span: 24,
            rows: 4,
          },
        ],
      },
      partsTableData: [],
      partsDetails: {
        title: "更换零部件",
        select: false,
        addMethons: true,
        maxHeight: 400,
        btnArr: ["add"], //"edit",
        column: [
          // {
          //   label: "备件名称",
          //   prop: "partName",
          //   required: true,
          //   type: "text"
          // },

          {
            label: "备件名称",
            prop: "partName",
            type: "autocomplete",
            clearable: true,
            required: true,
            changeMethods: (query, item, row) => {
              this.getSpareParts(query, row);
            },
          },
          {
            label: "规格",
            prop: "partModel",
            type: "text",
          },
          {
            label: "使用数量",
            prop: "partNum",
            required: true,
            type: "number",
            min: 1,
            precision: 0,
            step: 1,
          },
          {
            label: "单位",
            prop: "unit",
            type: "text",
            isHide: true,
          },
          {
            label: "单价",
            prop: "unitPrice",
            type: "text",
            min: 1,
            precision: 2,
            step: 1,
            isHide: true,
          },
          {
            label: "总价",
            prop: "totalPrice",
            type: "text",
            min: 1,
            precision: 0,
            step: 1,
            isHide: true,
          },
          {
            label: "品牌库",
            prop: "partBrand", //多选时，字段要为数组类型
            propArr: "brandArr",
            idsStr: "partBrandId",
            option: "brandOption",
            type: "equipmentBrand", //类型
            trigger: "change",
            methods: (obj, row) => {},
          },
          {
            label: "备件来源",
            prop: "partSource",
            type: "select",
            seleteOption: this.$store.getters["dirtData"]("order_part_source"),
            formatter: (val) => {
              return this.$store.getters["fineDirtDataName"](
                "order_part_source",
                val
              );
            },
            methods: (val, row) => {
              if (val == "spare_part") {
                this.getSpareParts("", row);
              }
            },
          },
        ],
        buttonArr: [
          {
            name: "删除",
            isShow: (row, index) => {
              return !this.hideBtn;
            },
            methods: (row, index) => {
              this.handleDelete(row, index);
            },
          },
        ],
      },
    };
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      this.listItemConfig.itemArr.map((i) => {
        if (this.hideBtn || this.showOnly) {
          //不可编辑
          i.disabled = true;
        } else {
          i.disabled = false;
        }
        if (
          this.orderType != "defect" &&
          [
            "equipmentName",
            "trueStatus",
            "majorId",
            "reasonType",
            "reason",
          ].includes(i.prop)
        ) {
          i.isHide = true;
        }
        if (i.prop == "outDispatch") {
          i.isHide = false;
        }
        if (i.prop == "reasonType") {
          i.required = false;
        }
      });
      this.partsDetails.column.map((i) => {
        if (["unit", "unitPrice", "totalPrice"].includes(i.prop)) {
          i.isHide = false;
        }
      });
      this.initData();
    },
    initData() {
      let data = JSON.parse(JSON.stringify(this.formData));
      if (data.factStartTime != undefined) {
        data.factTime = [data.factStartTime, data.factEndTime];
      } else {
        data.factTime = [];
      }
      //设置附件
      if (data.orderExecuteId) {
        this.attachSetting.businessId = this.formData.orderId;
        //此处的附件类型未执行信息的id
        this.attachSetting.businessType = this.formData.orderExecuteId;
        if (this.orderType == "defect") {
          this.imageSetting.businessId = this.formData.orderId;
          this.imageSetting.businessType = `image${this.formData.orderExecuteId}`;
        }
      }
      if (this.orderType == "overhaul") {
        this.attachSetting.businessId = this.formData.orderId;
        this.attachSetting.businessType = this.formData.id;
      }
      this.editFormData = Object.assign({}, data);
      if (this.editFormData == "1") {
        this.$set(this.listItemConfig.itemArr[10], "isHide", false);
      }
      let tableData = data.orderExecutePart || data.parts || [];

      tableData.map((i) => {
        if (this.hideBtn) {
          i.editable = false;
        } else {
          i.editable = true;
          i.brandOption = this.$utils.getOptionData(i.partBrand, i.partBrandId);
          i.brandArr = i.partBrandId;
        }
      });

      if (this.hideBtn) {
        //不可编辑
        let arr = [].concat(this.partsDetails.column);
        let nextArr = [];
        arr.map((i) => {
          if (i.prop != "action") {
            nextArr.push(i);
          }
        });
        this.partsDetails.column = nextArr;
      }
      // 缺陷工单-已归档-缺陷工单管理员岗位 可以修改执行信息的维护内容、更换零部件
      if (this.changeContent) {
        this.listItemConfig.itemArr[8].disabled = false;
        tableData.map((i) => {
          i.editable = true;
          i.brandOption = this.$utils.getOptionData(i.partBrand, i.partBrandId);
          i.brandArr = i.partBrandId;
        });
      }
      this.$nextTick(() => {
        this.$refs.partsTable.setTableData(tableData);
      });
    },
    //限制时间范围
    setTimeLimit() {
      this.listItemConfig.itemArr.map((i) => {
        if (i.prop == "factTime") {
          i.pickerOptions = {
            disabledDate(time) {
              // let { startTime, endTime } = this.defaultData;
              // let start = new Date(startTime).getTime();
              // let end = new Date(endTime).getTime();
              // return time.getTime() <= end && time.getTime() >= end;
            },
          };
        }
      });
    },
    //获取表单信息
    getFormData(data) {
      return this.$refs.listItemForm.getFormData(data);
    },
    //获取
    getPartsData() {
      return this.$refs.partsTable.getTableData();
    },
    //保存附件
    saveAttach() {
      if (this.orderType == "defect") {
        this.$refs.imageFile.save();
      }
      if (this.attachSetting.businessType) {
        this.$refs.performFile.save();
      } else {
        console.log("未设置businessType");
      }
    },
    //设备带出设备管理单位以及专业
    async setDeptManage(form) {
      let res = await getPresetParamsApi(form);
      let majorObj = res.data["0008000"] || {}; //专业“0008000”
      if (!(JSON.stringify(majorObj) == "{}")) {
        let { paramResult } = majorObj;
        this.$refs.listItemForm.setFormItem("majorId", paramResult);
      } else {
        this.$refs.listItemForm.setFormItem("majorId", "");
      }
    },
    setAttachType(data) {
      new Promise((resolve, reject) => {
        this.attachSetting.businessId = this.formData.orderId;
        this.attachSetting.businessType = data;
        if (this.orderType == "defect") {
          this.imageSetting.businessId = this.formData.orderId;
          this.imageSetting.businessType = `image${data}`;
        }
        resolve(this.attachSetting);
      }).then(() => {
        this.saveAttach();
      });
    },
    //根据是否是外单位改变界面显示
    changeConfig(obj) {
      let itemArr = this.listItemConfig.itemArr;
      for (let i in itemArr) {
        if (itemArr[i].prop == "legacyConet") {
          if (obj.value == 1) {
            //有遗留问题
            itemArr[i].isHide = false;
          } else {
            itemArr[i].isHide = true;
          }
        }
      }
    },
    //点击新增零部件
    addParts(data, hadData) {
      let rowIndex = this.partsTableData.rowIndex;
      data.rowIndex = hadData.length + 1;
      data.partNum = 1;
      // data.partSource = "spare_part";
      // data.action = "删除";
      hadData.push(data);
      this.$refs.partsTable.setTableData(hadData);
    },
    //点击删除按钮
    async handleDelete(row, num) {
      let listArr = [];
      let data = await this.$refs.partsTable.getTableData(false);
      data.map((i, index) => {
        if (index != num) {
          i.editable = true;
          listArr.push(i);
        }
      });
      this.$refs.partsTable.setTableData(listArr);
      // return this.$refs.partsTable.deleteItiem(row.rowIndex);
    },
    async getSpareParts(name, row) {
      if (row.partSource == "spare_part") {
        //如果是备件来源是备件备品
        let res = await serchEqBackup({ name });
        let data = res.data.list || [];
        let option = [];
        if (data.length > 0) {
          data.map((i) => {
            let obj = {
              label: i.name,
              value: i.name,
            };
            option.push(obj);
          });
        }
        this.$set(row, "selectOption", option);
      }
    },
    deleteAttach() {
      this.$refs.performFile.deleteTypeFiles();
    },
    //获取完工图片附件
    getImageFile() {
      return this.$refs.imageFile.getFileListData();
    },
  },
};
</script>

<style lang="less">
.add-block {
  padding: 0 10px 10px 10px;
  border: 1px solid #e1e1e1; //dotted
  margin-top: 10px;
  border-radius: 8px;
  background-color: #fff;

  .add-title {
    text-align: left;
  }
  .top-botton {
    display: flex;
    justify-content: space-between;
    align-items: center;
    line-height: 36px;
  }
  .attachConten {
    margin-top: 15px;
    display: flex;
    flex-flow: wrap nowrap;
    .redPoint {
      color: red;
    }
    .attachTitle {
      width: 120px;
    }
    .tebleDiv {
      width: 100%;
    }
  }
}
.el-date-editor .el-range-input {
  background-color: rgba(255, 255, 255, 0) !important;
}
.add-block + .add-block {
  margin-top: 40px;
}
.tableConten {
  display: flex;
  flex-flow: wrap nowrap;
  .itemTitle {
    width: 80px;
  }
  .tebleDiv {
    width: 100%;
  }
}
.redPoint {
  color: red;
}
</style>
